/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */


var EXPORTED_SYMBOLS =
[
    "callLater",
    "commonPrefix",
    "compare",
    "extend",
    "getFile",
    "lazyInit",
    "ListenerManager",
    "PATH_DELIM",
    "Set",
    "StringBundle",
];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");


const PATH_DELIM = ((Services.appinfo.OS == "WINNT") ? "\\" : "/");


// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Inheritance
function extend(child, supertype)
{
    child.prototype.__proto__ = supertype.prototype;
}

function lazyInit(obj, name, value)
{
    delete obj[name];
    obj[name] = value;
    return value;
}

function compare(a, b)
{
    return a.compareTo(b);
}

function commonPrefix(a, b)
{
    var i = 0;
    var n = Math.min(a.length, b.length);
    while ((i < n) && (a[i] == b[i]))
        i++;
    
    return a.substr(0, i);
}

function callLater(delay, obj, func, args)
{
    if (typeof(func) != "function")
        throw new Error("callLater: function is not function: " + func);
    
    if (! ((args == undefined) || Array.isArray(args)))
        throw new Error("callLater: args is not an Array: " + args);
    
    var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
    var callback = {notify: function() { func.apply(obj, args); }}
    timer.initWithCallback(callback, delay, Ci.nsITimer.TYPE_ONE_SHOT);
    return timer;
}

function getFile(path)
{
    try
    {
        if (! path)
            return null;
        
        if (path.charAt(0) != "$")
        {
            let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);  
            file.initWithPath(path);
            return file;
        }
        
        let unixPath = path.replace("\\", "/");
        let index = unixPath.indexOf("/");
        index = ((index != -1) ? index : unixPath.length);
        let name = unixPath.substring(1, index);
        unixPath = unixPath.substring(index + 1);
        
        let file = Services.dirsvc.get(name, Ci.nsIFile);
        for each (let p in unixPath.split("/"))
            if (p)
                file.append(p);
        
        return file;
    }
    catch (e)
    {
        Cu.reportError(e);
        Services.console.logStringMessage(e.message + " - path: '" + path + "'");
        return null;
    }
}


function Set(arr)
{
    for each (var value in arr)
        this[value] = true;
}


function StringBundle(url)
{
    this.bundle = Services.strings.createBundle(url);
}

StringBundle.prototype =
{
    get getter()
    {
        let self = this;
        return function(key, params /* ... */) { return self.get.apply(self, arguments); };
    },
    
    get: function(key, params /* ... */)
    {
        if (params)
        {
            params = Array.prototype.slice.call(arguments, 1);
            return this.formatStringFromName(key, params, params.length);
        }
        else
            return this.GetStringFromName(key);
    },
    
    // nsIStringBundle
    
    GetStringFromName: function(key)
    {
        try       { return this.bundle.GetStringFromName(key); }
        catch (e) { return key; }
    },
    
    formatStringFromName: function(key, params, paramsLength)
    {
        try       { return this.bundle.formatStringFromName(key, params, paramsLength); }
        catch (e) { return "(" + key + ", " + params + ", " + paramsLength + ")"; }
    },
}


function ListenerManager()
{
    // empty
}

ListenerManager.prototype =
{
    addListener: function(callback)
    {
        if (! this._listeners)
            this._listeners = [];
        var index = this._listeners.indexOf(callback);
        if (index == -1)
            this._listeners.push(callback);
        return callback;
    },
    
    removeListener: function(callback)
    {
        var index = (this._listeners ? this._listeners.indexOf(callback) : -1);
        var found = (index != -1);
        if (found)
            this._listeners.splice(index, 1);
        return found;
    },
    
    notifyListeners: function(/* args... */)
    {
        if (this._listeners)
            for each (var callback in this._listeners)
                try
                {
                    callback.apply(null, arguments);
                }
                catch (e)
                {
                    Cu.reportError(e);
                }
    }
}
